/* eslint-disable camelcase */
<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb class="navigation">
      <el-breadcrumb-item :to="{ path: '/mapu' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>申请门牌</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 主体区域 -->
    <!-- 门牌申请 -->
    <el-card class="notice">
      <h4>&nbsp;&nbsp;门牌申请</h4>
      <el-form :model="infoForm" ref="infoForm" :rules="rules" class="open" label-width="auto">
        <el-form-item label="身份证号:" prop="idNumber">
          <el-input v-model="infoForm.idNumber" clearable style="width: 52%"></el-input>
        </el-form-item>
        <el-form-item label="拥有人姓名:" prop="username">
          <el-input v-model="infoForm.username" clearable type="text" style="width: 52%"></el-input>
        </el-form-item>
        <el-form-item label="联系电话:" prop="telephone">
          <el-input v-model="infoForm.telephone" clearable type="num" style="width: 52%"></el-input>
        </el-form-item>
        <el-form-item label=" 门牌类型:" prop="type_name">
          <el-select v-model="infoForm.type_name" style="width: 52%" placeholder="请选择门牌类型">
            <el-option v-for="item in list" :key="item.type_name" :value="item.type_name">
              {{ item.type_name }}
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="具体地址：" prop="location">
          <baidu-map :style="mapStyle" ak="tyGBxrYAXHXpD2lTCLyTbmagHmxGV01d" :map-click="false" :center="center"
            :zoom="zoom" :scroll-wheel-zoom="true" @click="getClickInfo" @moving="syncCenterAndZoom"
            @moveend="syncCenterAndZoom" @ready="onBaiduMapReady" @zoomend="syncCenterAndZoom">
            <bm-view style="width: 52%; height: 100%;" />
            <bm-marker :position="{ lng: center.lng, lat: center.lat }" :dragging="true"
              animation="BMAP_ANIMATION_BOUNCE" />
            <bm-control :offset="{ width: '10px', height: '10px' }">
              <bm-auto-complete v-model="keyword" :sug-style="{ zIndex: 999999 }">
                <el-input v-model="keyword" type="text" placeholder="请输入地名关键字" clearable>
                  <i slot="prefix" class="el-input__icon el-icon-search" />
                </el-input>
              </bm-auto-complete>
            </bm-control>
            <bm-geolocation anchor="BMAP_ANCHOR_BOTTOM_RIGHT" show-address-bar auto-location />
            <bm-local-search :keyword="keyword" :auto-viewport="true" :panel="false" />
          </baidu-map>
        </el-form-item>
        <el-form-item label=" 申请理由:" prop="reason" style="width: 82%">
          <div id="editor" style="width: 100%;"></div>
        </el-form-item>
        <el-form-item style="width: 52%">
          <el-button type="primary" icon="el-icon-edit" @click="submitForm('infoForm')">提交申报</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import E from 'wangeditor'
import { BaiduMap, BmControl, BmView, BmAutoComplete, BmLocalSearch, BmMarker, BmGeolocation } from 'vue-baidu-map' // 引用，调整图片大小
export default {
  name: 'Applicate',
  components: {
    BaiduMap,
    BmControl,
    BmView,
    BmAutoComplete,
    BmLocalSearch,
    BmMarker,
    BmGeolocation
  },
  props: {
    // 在子组件中使用 props 选项去接收来自父组件传递过来的数据
    dialogVisible: Boolean,
    mapHeight: {
      type: Number,
      default: 300
    },
    title: {
      type: String,
      default: '选择目标位置'
    },
    width: {
      type: [Number, String],
      default: '85%'
    },
    height: {
      type: [Number, String],
      default: '80%'
    }
  },
  data () {
    // 电话号码校验
    var validatePass3 = (rule, value, callback) => {
      if (value && (!(/^[1][345789]\d{9}$/).test(value) || !(/^[1-9]\d*$/).test(value) || value.length !== 11)) {
        callback(new Error('手机号码不符合规范'))
      } else {
        callback()
      }
    }
    // 身份证号校验
    var checkIdNum = (rule, value, callback) => {
      const reg = /(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$)/
      if (!value) {
        return callback(new Error('身份证号不能为空！'))
      } else if (!reg.test(value)) {
        return callback(new Error('身份证号格式不正确！'))
      } else {
        callback()
      }
    }
    return {
      infoForm: {
        idNumber: '',
        username: '',
        telephone: '',
        type_name: '',
        location: '',
        reason: '',
        lat: '',
        lng: ''
      },
      editor: '',
      msg: {
        msg: ''
      },
      list: [],
      rules: {
        telephone: [
          { required: true, message: '请输入电话号码', trigger: 'blur' },
          { validator: validatePass3, trigger: 'blur' }
        ],
        idNumber: [
          { required: true, message: '请输入身份证号', trigger: 'blur' },
          { validator: checkIdNum, trigger: 'blur' }
        ],
        username: [
          { required: true, message: '请输入拥有人姓名', trigger: 'blur' }
        ],
        type_name: [
          { required: true, message: '请选择门牌类型', trigger: 'blur' }
        ]
      },
      // 地图
      BMap: null, // 地图组件是否就绪
      showMapComponent: this.dialogVisible,
      keyword: '', // 地区搜索的信息
      mapStyle: {
        width: '100%',
        height: this.mapHeight + 'px'
      },
      center: { lng: 116.404, lat: 39.915 },
      choosedLocation: { province: '', city: '', district: '', addr: '' },
      zoom: 15,
      editorOption: {
        placeholder: '请输入申请理由',
        theme: 'snow',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'], // 加粗，斜体，下划线，删除线
            [{ 'header': 1 }, { 'header': 2 }], // 标题，键值对的形式；1、2表示字体大小
            // eslint-disable-next-line standard/object-curly-even-spacing
            [{ 'list': 'ordered' }, { 'list': 'bullet' }], // 列表
            // eslint-disable-next-line standard/object-curly-even-spacing
            [{ 'script': 'sub' }, { 'script': 'super' }], // 上下标
            // eslint-disable-next-line standard/object-curly-even-spacing
            [{ 'indent': '-1' }, { 'indent': '+1' }], // 缩进
            [{ 'direction': 'rtl' }], // 文本方向
            [{ 'size': ['small', false, 'large', 'huge'] }], // 字体大小
            [{ 'header': [1, 2, 3, 4, 5, 6, false] }], // 几级标题
            [{ 'color': [] }, { 'background': [] }], // 字体颜色，字体背景颜色
            [{ 'font': [] }], // 字体
            [{ 'align': [] }], // 对齐方式
            ['clean'], // 清除字体样式
            ['image', 'video'] // 上传图片、上传视频
          ],
          imageResize: {
            displayStyles: {
              backgroundColor: 'black',
              border: 'none',
              color: 'white'
            },
            modules: ['Resize', 'DisplaySize', 'Toolbar']
          }
        }
      }
    }
  },
  watch: {
    value: function () {
      this.infoForm.reason = this.value
    }
  },
  mounted () {
    // 请求下拉框数据
    this.getSelect()
    this.setWangEditor()
  },
  methods: {
    // 请求门牌类型数据
    getSelect () {
      this.$axios.get('htype')
        .then(res => {
          if (res.data) {
            this.list = res.data.data
          }
        })
        .catch((err) => {
          console.log(err)
        })
    },
    // ready事件：在你需要二次开发或手动控制其子组件，可以使用在此事件中使用返回的 BMap 类和 map 实例进行手动控制
    onBaiduMapReady (e) {
      // console.log('返回BMap类和map实例', e)
      const that = this
      this.BMap = e.BMap
      if (this.BMap) {
        // 获取定位地址信息并赋值给声明变量
        const geolocation = new this.BMap.Geolocation()
        // 通过 getCurrentPosition() 方法：获取当前的位置信息
        geolocation.getCurrentPosition(res => {
          // console.log('返回详细地址和经纬度', res)
          const { lng, lat } = res.point
          // eslint-disable-next-line camelcase
          const { province, city, district, street, street_number } = res.address
          that.lat = res.point.lat
          that.lng = res.point.lng
          that.center = { lng, lat }
          // eslint-disable-next-line camelcase
          that.choosedLocation = { province, city, district, addr: street + street_number, lng, lat }
        })
      }
    },
    // 地图点击事件
    getClickInfo (e) {
      // 调整地图中心位置
      this.center.lng = e.point.lng
      this.center.lat = e.point.lat

      // 此时已经可以获取到BMap类
      if (this.BMap) {
        const that = this
        // Geocoder() 类进行地址解析
        // 创建地址解析器的实例
        const geoCoder = new this.BMap.Geocoder()
        // getLocation() 类--利用坐标获取地址的详细信息
        // getPoint() 类--获取位置对应的坐标
        geoCoder.getLocation(e.point, function (res) {
          // console.log('获取经纬度', e.point, '获取详细地址', res)
          const addrComponent = res.addressComponents
          const surroundingPois = res.surroundingPois
          const province = addrComponent.province
          const city = addrComponent.city
          const district = addrComponent.district
          let addr = addrComponent.street
          if (surroundingPois.length > 0 && surroundingPois[0].title) {
            if (addr) {
              addr += `-${surroundingPois[0].title}`
            } else {
              addr += `${surroundingPois[0].title}`
            }
          } else {
            addr += addrComponent.streetNumber
          }
          that.choosedLocation = { province, city, district, addr, ...that.center }
        })
      }
    },
    syncCenterAndZoom (e) {
      // 返回地图当前的缩放级别
      this.zoom = e.target.getZoom()
    },
    // 提交申请
    submitForm (infoForm) {
      this.$refs[infoForm].validate((valid) => {
        if (valid) {
          let param = {
            applyIdnum: this.infoForm.idNumber,
            applyName: this.infoForm.username,
            applyTele: this.infoForm.telephone,
            applyHtypename: this.infoForm.type_name,
            applyReason: this.editor.txt.html(),
            applyLat: this.lat,
            applyLng: this.lng
          }
          this.$axios({
            url: 'pogapply-record',
            method: 'post',
            data: param
          }).then(res => {
            console.log(res.data)
            if (res.data.code === 200) {
              this.$message.success(res.data.message)
              this.$refs[infoForm].resetFields()
            }
          })
            .catch((err) => {
              console.log(err)
            })
        }
      })
    },
    setWangEditor () {
      // 创建编辑器
      this.editor = new E('#editor')
      this.editor.config.height = 500
      // 配置 onchange 回调函数
      this.editor.config.onchange = function (newHtml) {
        console.log('change 之后最新的 html', newHtml)
      }
      // 配置触发 onchange 的时间频率，默认为 200ms
      this.editor.config.onchangeTimeout = 500 // 修改为 500ms
      // 插入网络图片的回调
      this.editor.config.linkImgCallback = function (src) {
        console.log('图片 src ', src)
        // console.log('图片文字说明',alt)
        // console.log('跳转链接',href)
      }
      // 自定义检查插入视频的回调
      this.editor.config.onlineVideoCallback = function (video) {
        // 自定义回调内容，内容成功插入后会执行该函数
        console.log('插入视频内容', video)
      }
      this.editor.config.showLinkImg = false
      // 关闭样式过滤
      this.editor.config.pasteFilterStyle = false
      // 配置 server 接口地址
      this.editor.config.uploadImgServer = 'http://127.0.0.1:8888/api/qiniu/image'
      this.editor.config.uploadImgHeaders = { 'Authorization': sessionStorage.getItem('token') }
      this.editor.config.withCredentials = true
      this.editor.config.uploadFileName = 'file'
      this.editor.config.uploadImgMaxSize = 5 * 1024 * 1024 // 最大上传5M的图片
      this.editor.config.uploadImgMaxLength = 5 // 一次最多上传 1 个图片
      this.editor.config.uploadImgHooks = {
        before: function (xhr, editor, files) {

        },
        success: function (xhr, editor, result) {
          console.log('上传成功')
        },
        fail: function (xhr, editor, result) {
          console.log('上传失败,原因是' + result)
        },
        error: function (xhr, editor) {
          console.log('上传出错')
        },
        timeout: function (xhr, editor) {
          console.log('上传超时')
        },
        customInsert: function (insertImg, result, editor) {
          var url = result.data.path
          insertImg(url)
        }
      }
      // this.editor.config.uploadImgShowBase64 = true
      // 配置alt选项
      this.editor.config.showLinkImgAlt = false
      // 配置图片超链接
      this.editor.config.showLinkImgHref = false
      this.editor.create()
    },
    ShowContent () {
      alert(this.editor.txt.html())
      // alert(this.editor.txt.text())
    },
    UploaderByAxios () {
      const _this = this
      this.msg.msg = this.editor.txt.html()
      alert(_this.msg.msg)
      this.$axios.post('qiniu/image', _this.msg).then(function (resp) {
        alert(resp.data)
      })
    }
  }
}
</script>

<style scoped>
.navigation {
  padding: 10px;
}

.notice {
  margin-bottom: 40px;
  border-radius: 15px;
  box-shadow: 15px 15px 10px -12px #4c61a0;
}

h4 {
  padding-bottom: 8px;
  margin-bottom: 20px;
  border-bottom: 2px solid #4c61a0;
}

.open {
  margin-left: 13%;
  margin-top: 30px;
}
</style>
